package cn.lopr.im.api.configuration;

import cn.lopr.im.api.annotation.Auth;
import cn.lopr.im.api.bean.User;
import cn.lopr.im.api.exception.AuthException;
import cn.lopr.im.api.service.IAuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shuangyang7
 * @date 2021/5/15 16:36
 */
@Configuration
public class ApplicationInterceptor extends HandlerInterceptorAdapter {

    private final static Logger logger = LoggerFactory.getLogger(ApplicationInterceptor.class);

    @Autowired
    private IAuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        logger.info(String.format("Remote host: %s; Request url: %s;",
                request.getRemoteHost(), request.getRequestURL().toString()));

        String authorization = request.getHeader("Authorization");

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        if (!handlerMethod.hasMethodAnnotation(Auth.class)) {
            return true;
        }

        if (StringUtils.isEmpty(authorization) || !authorization.startsWith("IM")) {
            throw new AuthException("请先登陆哦~~~~");
        }

        if (!authService.refreshToken(authorization)) {
            throw new AuthException("权限认证失败");
        }
        User user = authService.getInfoByToken(authorization);
        logger.info(String.format("current user: %s", user.getPhone()));
        AuthInfo.set(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        AuthInfo.remove();
    }

}
